package org.ouwh.oowiki;

import java.io.FileReader;
import java.util.HashMap;
import java.util.Properties;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class Shutdown {
	public static void main(String[] args) {
		Shutdown sd = new Shutdown();
		sd.shutdown(Startup.class);
	}

	public void shutdown(Class<?> clazz) {
		JMXConnector jmxConn = null;
		try {
			Properties props = new Properties();
			FileReader in = null;
			try {
				in = new FileReader(System.getProperty("org.ouwh.oowiki.jmxfile", "etc/management.properties"));
				props.load(in);
			} finally {
				try {
					in.close();
				} catch (Exception e) {
				}
			}
			JMXServiceURL jmxUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:"
					+ props.getProperty("com.sun.management.jmxremote.port") + "/" + "jmxrmi");
			String tokenPostFix = props.getProperty("com.sun.management.jmxremote.token");
			HashMap<String, Object> params = new HashMap<String, Object>();
			String[] credentials = new String[] { "oowikiadmin", "ouwh_oowiki_202408" + tokenPostFix };
			params.put("jmx.remote.credentials", credentials);
			jmxConn = JMXConnectorFactory.connect(jmxUrl, params);
			MBeanServerConnection mbsConn = jmxConn.getMBeanServerConnection();
			ObjectName objname = new ObjectName(clazz.getPackage().getName() + ":name=" + clazz.getSimpleName());
			Object[] para = {};
			String[] paraType = {};
			mbsConn.invoke(objname, "shutdown", para, paraType);
			System.out.println("shutdown server success.");
		} catch (Exception e) {
			System.out.println("shutdown server failed: ");
			e.printStackTrace(System.out);
		} finally {
			try {
				jmxConn.close();
			} catch (Exception e) {
			}
		}
	}
}
